import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:creatures_world/framework/custom/ext_widget/widget_util.dart';
import 'package:creatures_world/framework/ext_dart/map_ext.dart';
import 'package:creatures_world/get/routers.dart';
import 'package:creatures_world/pages/base/base_page.dart';
import 'package:creatures_world/pages/home/home_controller.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:getwidget/getwidget.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';

import '../../framework/utils/sized_box_util.dart';

class HomePage extends BasePage<HomeController> {
  final EasyRefreshController _controller = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);
  ScrollController scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Container(
        child: Stack(
          children: [
            /*   Transform.scale(
              scaleX: 1.5,
              scaleY: 1.5,
              child: AspectRatio(aspectRatio: 9 / 16, child: Image.asset("images/bg_home_animals.png", fit: BoxFit.fitHeight)),
            ),
         */
            Container(
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    color: Colors.blueAccent,
                    child: Column(
                      children: [
                        sb.h(MediaQuery.of(context).padding.top),
                        Container(
                          child: Stack(
                            alignment: Alignment.topCenter,
                            children: [
                              Column(
                                children: [
                                  Container(
                                    height: 40.h,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      children: [
                                        sb.w(15.w),
                                        Icon(Icons.search, size: 25.w, color: Colors.white).prop(
                                          onTap: () {
                                            Get.toNamed(AppPage.ROUTER_FUNC);
                                          },
                                        ),
                                        Text("Bio Adventure", style: GoogleFonts.aBeeZee(fontSize: 16.sp, color: Colors.white, fontWeight: FontWeight.w800)),
                                        Obx(() {
                                          if (controller.totalAnimalsTypes.value == 0) {
                                            return sb.z();
                                          }
                                          String spNo = NumberFormat('#,###').format(controller.totalAnimalsTypes.value);
                                          return Text(
                                            " (${spNo} species)",
                                            style: GoogleFonts.poppins(fontWeight: FontWeight.w500, color: Colors.white, fontSize: 12.sp),
                                          );
                                        }),
                                        Spacer(),
                                        Icon(Icons.star, color: Colors.white).prop(onTap: () {
                                          Get.toNamed(AppPage.ROUTER_FAVOR);
                                        }),
                                        sb.w(15.w),
                                      ],
                                    ),
                                  ),
                                  Obx(() {
                                    //顶部的类别
                                    List<Widget> tabs =
                                        controller.spKinds.value.map((e) {
                                          bool checked = e["checked"] as bool;
                                          return Container(
                                            alignment: Alignment.center,
                                            margin: EdgeInsets.only(left: 5.w, right: 5.w, top: 10.h),
                                            decoration: BoxDecoration(
                                              border: Border(
                                                bottom: BorderSide(
                                                  color: checked ? Colors.white : Colors.grey, // 颜色
                                                  width: 2.0, // 边框宽度
                                                ),
                                              ),
                                            ),
                                            child: Column(
                                              children: [
                                                Image.asset("images/${e["icon"]}", width: 30),
                                                Text(
                                                  "${e["name"]}",
                                                  style: GoogleFonts.cabin(fontWeight: FontWeight.w400, color: Colors.white, fontSize: 17.sp),
                                                ),
                                              ],
                                            ).prop(
                                              onTap: () {
                                                e["checked"] = true;
                                                for (var ex in controller.spKinds.value) {
                                                  if (ex == e) {
                                                    ex["checked"] = true;
                                                  } else {
                                                    ex["checked"] = false;
                                                  }
                                                }
                                                controller.spKinds.value = List.of(controller.spKinds.value);
                                                controller.onSpChecked(e);
                                              },
                                            ),
                                          );
                                        }).toList();
                                    return Container(
                                      margin: EdgeInsets.only(left: 5.w, right: 5.w),
                                      child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Row(children: tabs)),
                                    );
                                  }),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Obx(() {
                      int typeLength = controller.animalsTypes.length;
                      bool showGrid = controller.showGridOrlist.value;
                      if (typeLength == 0) {
                        return SizedBox(width: 200, height: 200, child: Center(child: CircularProgressIndicator()));
                      }

                      return EasyRefresh.builder(
                        header: ClassicHeader(),
                        footer: ClassicFooter(),
                        controller: _controller,
                        onRefresh: () async {
                          await controller.loadSpecies(true);
                          _controller.finishRefresh();
                          _controller.resetFooter();
                        },
                        onLoad: () async {
                          int addCount = await controller.loadSpecies(false);
                          if (addCount == 0) {
                            _controller.finishLoad(IndicatorResult.noMore);
                          } else {
                            _controller.finishLoad(IndicatorResult.success);
                          }
                        },
                        childBuilder: (context, physics) {
                          return buildGridView(typeLength, physics);
                        },
                      );
                    }),
                  ),
                  sb.h(10.h),
                ],
              ),
            ),

            Align(
              alignment: Alignment.bottomRight,
              child: Container(
                margin: EdgeInsets.all(25.w),
                child: ClipOval(
                  child: Container(
                    width: 50.w,
                    height: 50.w,
                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(50.w), color: Colors.blueAccent),
                    alignment: Alignment.center,
                    child: Text("Top", style: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white)),
                  ).prop(
                    onTap: () {
                      double maxScroll = scrollController.position.maxScrollExtent;
                      double currentScroll = scrollController.position.pixels;
                      if (currentScroll == 0) {
                        GFToast.showToast("Already at the top.", context, toastPosition: GFToastPosition.CENTER);
                      } else {
                        scrollController.animateTo(0.0, duration: Duration(milliseconds: 300), curve: Curves.easeOut);
                      }
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildGridView(int typeLength, physics) {

    if (controller.showGridOrlist.value) {

      return GridView.builder(

        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, // 每行3个
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        physics: physics,
        controller: scrollController,
        padding: EdgeInsets.zero,
        itemCount: typeLength,
        itemBuilder: (context, index) {


          Map<String, dynamic> data = controller.animalsTypes.value[index];
          Map<String, dynamic> taxon = data["taxon"];
          Map<String, dynamic> defaultPhoto = taxon["default_photo"];

          String count = data.nn("count");
          String name = taxon.nn2("preferred_common_name");
          String spName = taxon.nn2("name");
          String url =  defaultPhoto["medium_url"]??defaultPhoto["url"];

          return Container(
            child: Stack(
              children: [

                Container(
                  width: double.infinity,
                  height: double.infinity,
                  child: CachedNetworkImage(
                    imageUrl: url,
                    fit: BoxFit.cover,
                    placeholder: (ctx, url) {
                      return Image.asset("images/image_place_holder.png", fit: BoxFit.cover);
                    },
                    errorWidget: (BuildContext context, String url, Object error) {
                      return Image.asset("images/image_place_holder.png", fit: BoxFit.cover);
                    },
                  ),
                ),

                Column(
                  children: [
                    Spacer(),
                    ClipRRect(
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 20.0, sigmaY: 20.0),
                        child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.all(3.w),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                "${name}",
                                maxLines: 2,
                                textAlign: TextAlign.center,
                                style: GoogleFonts.poppins(fontSize: 12.sp, color: Colors.white, fontWeight: FontWeight.w600),
                              ),

                              /* Text(
                                "${spName}",
                                maxLines: 2,
                                textAlign: TextAlign.start,
                                style: GoogleFonts.poppins(fontSize: 10.sp, color: Colors.white, fontWeight: FontWeight.w600),
                              ),*/

                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ).prop(
            onTap: () {
              gotoSpeciDetail(data);
            },
          );
        },
      );
    } else {
      return ListView.separated(
        padding: EdgeInsets.zero,
        physics: physics,
        itemBuilder: (ctx, index) {
          Map<String, dynamic> data = controller.animalsTypes.value[index];
          Map<String, dynamic> taxon = data["taxon"];
          Map<String, dynamic> defaultPhoto = taxon["default_photo"];

          String count = data.nn("count");
          String name = taxon.nn2("preferred_common_name");
          String spName = taxon.nn2("name");
          String url = defaultPhoto["url"];

          return Row(
            children: [
              sb.w(10.w),
              Container(width: 80.w, height: 80.w, child: CachedNetworkImage(imageUrl: url, fit: BoxFit.cover)),
              sb.w(10.w),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "${name}",
                    maxLines: 2,
                    textAlign: TextAlign.start,
                    style: GoogleFonts.poppins(fontSize: 16.sp, color: Colors.black, fontWeight: FontWeight.w600),
                  ),
                  sb.h(10.h),
                  Text(
                    "${spName}",
                    maxLines: 2,
                    textAlign: TextAlign.start,
                    style: GoogleFonts.poppins(fontSize: 16.sp, color: Colors.black.withAlpha(100), fontWeight: FontWeight.w600),
                  ),
                ],
              ),
            ],
          ).prop(
            onTap: () {
              gotoSpeciDetail(data);
            },
          );
        },

        separatorBuilder: (ctx, index) {
          return Divider();
        },
        itemCount: controller.animalsTypes.value.length,
      );
    }
  }

  gotoSpeciDetail(dynamic spData) {
    Get.toNamed(AppPage.ROUTER_SPDETAIL, arguments: {"data": spData});
  }
}
